/** 
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.merchant.web;

import cn.horesman.service.HoresmanService;
import cn.itcast.pojo.*;
import cn.itcast.util.CookieUtil;
import cn.itcast.util.OutputStringController;
import cn.itcast.util.WechatUtil;
import cn.merchant.service.merchantService;
import cn.web.web_module.util.IconPath;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.itcast.util.OrderNumber.getOrderIdByTime;

/**
 * @title: homeController.java
 * @package com.job.controller
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2020年3月18日 下午8:57:15
 * @version: V1.0
*/
@Slf4j
@RestController
@RequestMapping(value="/wxshop/merchant",produces="text/html;charset=UTF-8")
public class merchantController {

	@Resource
	HoresmanService horesmanService;

	@Resource
	merchantService merchantService;
	@Resource
    OutputStringController osc;
	@Resource
	cn.itcast.mapper.merchantMapper merchantMapper;
	@Resource
    CookieUtil cookieUtil;

	/**
	 * @title:   horseman
	 * @description: 骑手登录
	 * @param:  
	 * @throws:   
	 */
	@RequestMapping(value="/login", produces = "application/json;charset=UTF-8")
	public String login(@RequestBody Map<String,String> map) {
		String username = map.get("username");
		String password = map.get("password");
		//验证身份
		Map<String,Object> resultMap = merchantService.login(username,password);
		String results = "";
		if((boolean) resultMap.get("islogin")) {
			results = osc.resultSuccess("yes", resultMap.get("horsemen"));
		}else{
			results = osc.failure("no");
		}
		return results;
	}

	/**
	 * 微信用户登录详情
	 */
	@PostMapping("wxlogin")
	@ResponseBody
	public String user_login(@RequestParam(value = "code", required = false) String code,
							 @RequestParam(value = "merchantId", required = false) String merchantId,
							 @RequestParam(value = "rawData", required = false) String rawData,
							 @RequestParam(value = "signature", required = false) String signature,
							 @RequestParam(value = "encrypteData", required = false) String encrypteData,
							 @RequestParam(value = "iv", required = false) String iv) {
		// 用户非敏感信息：rawData
		// 签名：signature
		JSONObject rawDataJson = JSON.parseObject(rawData);
		log.debug(signature);
		// 1.接收小程序发送的code
		// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
		JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenIdToMerchant(code);
		// 3.接收微信接口服务 获取返回的参数
		String openid = SessionKeyOpenId.getString("openid");
		log.debug(openid);
		String sessionKey = SessionKeyOpenId.getString("session_key");

		// 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
		String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
		log.debug(signature2);
		if (!signature.equals(signature2)) {
			return osc.resultFailure( "签名校验失败", null);
		}
		// 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
		merchant merchant = merchantMapper.selectByPrimaryKey(Integer.parseInt(merchantId));
		// uuid生成唯一key，用于维护微信小程序用户与服务端的会话
		String skey = UUID.randomUUID().toString();


		Map<String,String> map = new HashMap<>();
		map.put("openId",openid);
		map.put("skey",skey);
		String result="";

		if (!StringUtils.isNotBlank(ObjectUtils.toString(merchant.getOpenId()))||!merchant.getOpenId().equals(openid)) {
			// 用户信息入库
			String nickName = rawDataJson.getString("nickName");
			String avatarUrl = rawDataJson.getString("avatarUrl");
			String gender = rawDataJson.getString("gender");
			String city = rawDataJson.getString("city");
			String country = rawDataJson.getString("country");
			String province = rawDataJson.getString("province");

			//horseman = new horseman();
			merchant.setOpenId(openid);
			merchant.setSkey(skey);
			merchant.setCreateTime(new Date());
			merchant.setLastVisitTime(new Date());
			merchant.setSessionKey(sessionKey);
			merchant.setCity(city);
			merchant.setProvince(province);
			merchant.setCountry(country);
			merchant.setAvatarUrl(avatarUrl);
			merchant.setGender((byte) Integer.parseInt(gender));
			merchant.setNickName(nickName);

			merchantMapper.updateByPrimaryKeySelective(merchant);
			if(merchant.getMerchantFid().equals(0)){
				account account = new account();
				account.setOpenId(openid);
				account.setAccountName(rawDataJson.getString("nickName"));
				account.setAccountTypeid(3);
				account.setAccountNumber("0301");

				//创建用户账户
				boolean isCreate = merchantService.createAccount(account);
				if(isCreate){
					return osc.resultSuccess("登录成功",map);
				}else {
					return osc.resultSuccess("登录成功，账户创建失败",map);
				}
			}


		} else {
			// 已存在，更新用户登录时间
			merchant.setLastVisitTime(new Date());
			// 重新设置会话skey
			merchant.setSkey(skey);
			merchantMapper.updateByPrimaryKeySelective(merchant);
		}

		result = osc.resultSuccess("登录成功",map);



		//encrypteData比rowData多了appid和openid
		//JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
		//6. 把新的skey返回给小程序

		return result;
	}



	/**
	 *
	 * @Description:
	 * 获取骑手各状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findMerchantOrder")
	public String findMerchantOrder(@RequestBody Map<String,String> map){
		log.debug("获取商户各状态订单！！！");
		String orderStatus = map.get("orderStatus");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<packageOrder> orders = merchantService.findMerchantOrder(orderStatus,openId);
		if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取用户各状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取用户各状态订单成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取骑手已完成状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresmanOverOrder")
	public String findHoresmanOverOrder(@RequestBody Map<String,String> map){
		log.debug("获取骑手各状态订单！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<List<order>> orders = merchantService.findHoresmanOverOrder(openId);
		if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取用户各状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取用户各状态订单成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 骑手接收订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/acceptOrder")
	public String acceptOrder(@RequestBody Map<String,String> map){
		log.debug("骑手接收订单！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		//返回结果
		String results ="";
		boolean isaccept= merchantService.acceptOrder(orderId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("骑手接收订单失败");
		} else {
			results = osc.resultSuccess("yes", "成功接收订单");
			log.debug("骑手接收订单成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 获取单个订单详细信息
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findOneOrder")
	public String findOneOrder(@RequestBody Map<String,String> map){
		log.debug("获取单个订单详细信息！！！");
		String orderId = map.get("orderId");
		//返回结果
		String results ="";
		packageOrder packageOrder = merchantService.findOneOrder(orderId);
		if (packageOrder==null) {
			results = osc.resultFailure("no", "");
			log.debug("获取单个订单详细信息失败");
		} else {
			results = osc.resultSuccess("yes", packageOrder);
			log.debug("获取单个订单详细信息成功");
		}
		return results;

	}



    /**
     *
     * @Description:
     * 骑手确认订单异常
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/abnormalOrder")
    public String abnormalOrder(@RequestBody Map<String,String> map){
        log.debug("骑手确认订单异常");
        //获取地址信息
        Integer orderId =Integer.parseInt(map.get("orderId"));
        String explain =map.get("explain");
        //返回结果
        String results = "";
        boolean isdelect = merchantService.abnormalOrder(orderId,explain);
        if(isdelect){
            results = osc.success("yes");
            log.debug("骑手确认订单异常成功");
        }else{
            results = osc.failure("no");
            log.debug("骑手确认订单异常失败");
        }

        return results;
    }


	/**
	 *
	 * @Description:
	 * 骑手取消订单
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/cancelOrder")
	public String cancelOrder(@RequestBody Map<String,String> map){
		log.debug("骑手取消订单");
		//获取地址信息
		Integer orderId =Integer.parseInt(map.get("orderId"));
		//返回结果
		String results = "";
		boolean isdelect = merchantService.cancelOrder(orderId);
		if(isdelect){
			results = osc.success("yes");
			log.debug("骑手取消订单成功");
		}else{
			results = osc.failure("no");
			log.debug("骑手取消订单失败");
		}

		return results;
	}

    /**
     *
     * @Description:
     * 修改用户数据
     * @auther: 欧阳辉
     * @date: 14:51 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody Map<String,String> map){
        log.debug("修改用户数据");
		merchant merchant = new merchant();

        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("openId")))){
			merchant.setOpenId(map.get("openId"));
		}
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userName")))){
			merchant.setNickName(map.get("userName"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(Byte.valueOf(map.get("gender"))))){
			merchant.setGender(Byte.valueOf(map.get("gender")));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("phone")))){
			merchant.setMerchantPhone(map.get("phone"));
        }
        if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userID")))){
			merchant.setMerchantIdNumber(map.get("userID"));
        }
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("name")))){
			merchant.setMerchantName(map.get("name"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("identitycard")))){
			merchant.setIdentitycard(map.get("identitycard"));
		}
        //返回结果
        String results = "";
        boolean isdelect = merchantService.updateUserInfo(merchant);
        if(isdelect){
            results = osc.success("yes");
            log.debug("修改用户数据成功");
        }else{
            results = osc.failure("no");
            log.debug("修改用户数据失败");
        }
        return results;
    }

	/**
	 *
	 * @Description:
	 * 商家完善信息
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/18
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updatemerchantmessage")
	public String updatemerchantmessage(@RequestBody Map<String,String> map){
		log.debug("完善商家信息");
		merchant merchant = new merchant();

		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("openId")))){
			merchant.setOpenId(map.get("openId"));
		}

		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("userID")))){
			merchant.setMerchantIdNumber(map.get("userID"));
		}

		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("merchantLat")))){
			merchant.setMerchantLat(map.get("merchantLat"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("merchantLon")))){
			merchant.setMerchantLon(map.get("merchantLon"));
		}

		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("receivingtype")))){
			merchant.setReceivingtype(map.get("receivingtype"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("companyname")))){
			merchant.setCompanyname(map.get("companyname"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("creditcode")))){
			merchant.setCreditcode(map.get("creditcode"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("license")))){
			merchant.setLicense(map.get("license"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("businessmodel")))){
			merchant.setBusinessmodel(map.get("businessmodel"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("companytel")))){
			merchant.setCompanytel(map.get("companytel"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("city")))){
			merchant.setCity(map.get("city"));
		}
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("identitycard")))){
			merchant.setIdentitycard(map.get("identitycard"));
		}

		//返回结果
		String results = "";
		boolean isdelect = merchantService.updatachantmessage(merchant);
		if(isdelect){
			results = osc.success("yes");
			log.debug("完善商户信息成功");
		}else{
			results = osc.failure("no");
			log.debug("完善商户信息失败");
		}
		return results;
	}


	/**
	 *
	 * @Description:
	 * 用户取消上门订单
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/30
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/cancelmerchant")
	public String cancelmerchant(@RequestBody Map<String,String> map){
		log.debug("用户取消上门订单");
		String ordernumber = map.get("ordernumber");
		//返回结果
		String results = "";
		boolean isdelect = merchantService.cancelmerchaent(ordernumber);
		if(isdelect){
			results = osc.success("yes");
			log.debug("取消订单成功");
		}else{
			results = osc.failure("no");
			log.debug("取消订单失败");
		}
		return results;
	}




	/**
	 *
	 * @Description:
	 * 查找用户数据
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findUserInfo")
	public String findUserInfo(@RequestBody Map<String,String> map){
		log.debug("查找用户数据");
		String openId = map.get("openId");

		//返回结果
		String results = "";
		merchant merchant = merchantService.findUserInfo(openId);
		if(merchant!=null){
			results = osc.resultSuccess("yes",merchant);
			log.debug("查找用户数据成功");
		}else{
			results = osc.failure("no");
			log.debug("查找用户数据失败");
		}

		return results;
	}

	/**
	 *
	 * @Description:
	 * 修改订单数据（订单称重）
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updateOrder")
	public String updateOrder(@RequestBody Map<String,String> map){
		log.debug("修改订单数据（订单称重）");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		double price = Double.parseDouble(map.get("price"));
		Date time = new Date();
		packageOrder packageOrder = new packageOrder();
		packageOrder.setId(orderId);
		packageOrder.setOrderSumRecycle(price);
		packageOrder.setClearTime(time);

		//返回结果
		String results = "";
		boolean isdelect = merchantService.updateOrder(packageOrder);
		if(isdelect){
			results = osc.success("yes");
			log.debug("修改订单数据（订单称重）成功");
		}else{
			results = osc.failure("no");
			log.debug("修改订单数据（订单称重）失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 修改订单详细数据（订单称重）
	 * @auther: 欧阳辉
	 * @date: 14:51 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updateOrderItem")
	public String updateOrderItem(@RequestBody Map<String,String> map){
		log.debug("修改订单详细数据（订单称重）");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		Integer id = Integer.parseInt(map.get("id"));
		int amount = 0;
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("amount")))){
			amount = Integer.parseInt(map.get("amount"));
		}

		double price = Double.parseDouble(map.get("price"));
		double unitPrice = Double.parseDouble(map.get("unitPrice"));
		double recycleWeigh = 0.00;
		if(StringUtils.isNotBlank(ObjectUtils.toString(map.get("recycleWeigh")))){
			recycleWeigh= Double.parseDouble(map.get("recycleWeigh"));
		}
		Date time = new Date();
		packageOrderItem packageOrderItem = new packageOrderItem();
		packageOrderItem.setId(id);
		packageOrderItem.setAmount(amount);
		packageOrderItem.setSumRecycle(price);
		packageOrderItem.setUnitPrice(unitPrice);
		packageOrderItem.setWeighTime(time);
		packageOrderItem.setRecycleWeigh(recycleWeigh);


		//返回结果
		String results = "";
		boolean isdelect = merchantService.updateOrderItem(packageOrderItem,orderId);
		if(isdelect){
			results = osc.success("yes");
			log.debug("修改订单详细数据（订单称重）成功");
		}else{
			results = osc.failure("no");
			log.debug("修改订单详细数据（订单称重）失败");
		}

		return results;
	}


	/**
	 *
	 * @Description:
	 * 生成订单
	 * @auther: 欧阳辉
	 * @date: 8:12 2020/3/17
	 * @param: [request]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("uploadOrder")
	public String uploadOrder(HttpServletRequest request) throws IllegalStateException, IOException {
		//返回结果
		String results="";

		//获取订单编号
		Integer id = Integer.parseInt(request.getParameter("id"));


		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		if(multipartResolver.isMultipart(request))
		{
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			//获取multiRequest 中所有的文件名
			Iterator iter=multiRequest.getFileNames();

			while(iter.hasNext())
			{
				//一次遍历所有文件
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if(file!=null)
				{
					SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
					String newDate=sdf.format(new Date());
					//服务器存储图片地址
					//服务器地址：“/usr/tomcat/images/dhn/icon/orderItem”
					//String filePath= "D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
//					String filePath= "/usr/tomcat/images/dhn/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();	//松注释
					String filePath= IconPath.ICONPATH +"icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					//String filePath="/usr/tomcat/images/wxshop/evaluate/"+request.getParameter("openId")+"/"+file.getOriginalFilename();
//					File files=new File("/usr/tomcat/images/dhn/icon/orderItem/"+newDate); //松注释

					File files=new File(IconPath.ICONPATH+"icon/orderItem/"+newDate);
					//File files=new File("D:/Desktop/icon/orderItem/"+newDate);
					if(!files.exists()){//如果文件夹不存在
						files.mkdir();//创建文件夹
					}
					//数据库存放访问地址
					//String path="D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					String path="https://www.dhnep.cn:8181/dhn/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
					boolean isadd = merchantService.addImgPath(path,id);
					if(isadd) {
						//上传图片至服务器
						file.transferTo(new File(filePath));
						results = osc.success("yes");
						log.debug("上传成功");
					}else {
						results = osc.failure("no");
						log.debug("上传失败");
					}

				}

			}

		}


		return results;
	}


	/**
	 *
	 * @Description:
	 * 添加order item
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/addOrderItem")
	public String addOrderItem(@RequestBody Map<String,String> map){
		log.debug("添加order item！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		Integer classifyId = Integer.parseInt(map.get("classifyId"));
		//返回结果
		String results ="";
		boolean isaccept= merchantService.addOrderItem(orderId,classifyId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("添加order item失败");
		} else {
			results = osc.resultSuccess("yes", "添加order item");
			log.debug("添加order item成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 删除order item
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/delectOrderItem")
	public String delectOrderItem(@RequestBody Map<String,String> map){
		log.debug("删除order item！！！");
		Integer orderId = Integer.parseInt(map.get("id"));
		//返回结果
		String results ="";
		boolean isaccept= merchantService.delectOrderItem(orderId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("删除order item失败");
		} else {
			results = osc.resultSuccess("yes", "删除order item");
			log.debug("删除order item成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 骑手支付订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/toPayByOrder")
	public String toPayByOrder(@RequestBody Map<String,String> map){
		log.debug("骑手支付订单！！！");
		Integer orderId = Integer.parseInt(map.get("orderId"));
		String openId = map.get("openId");
		//返回结果
		String results ="";
		boolean isaccept= merchantService.toPayByOrder(orderId,openId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("骑手支付订单失败");
		} else {
			results = osc.resultSuccess("yes", "骑手支付订单");
			log.debug("骑手支付订单成功");
		}
		return results;

	}
    /**
     *
     * @Description:
     * 商家完成订单
     * @auther: 欧阳辉
     * @date: 11:33 2020/3/17
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/finishOrder")
    public String finishOrder(@RequestBody Map<String,String> map){
        log.debug("商家完成订单订单！！！");
        Integer orderId = Integer.parseInt(map.get("orderId"));
        String openId = map.get("openId");
        //返回结果
        String results ="";
        boolean isaccept= merchantService.finishOrder(orderId,openId);
        if (!isaccept) {
            results = osc.resultFailure("no", "");
            log.debug("商家完成订单失败");
        } else {
            results = osc.resultSuccess("yes", "骑手支付订单");
            log.debug("商家完成订单成功");
        }
        return results;

    }


	/**
	 *
	 * @Description:
	 * 更新骑手位置
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/toLatAndLon")
	public String toLatAndLon(@RequestBody Map<String,String> map){
		log.debug("更新骑手位置！！");
		String lat = map.get("lat");
		String lon = map.get("lon");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		boolean isaccept= merchantService.toLatAndLon(lat,lon,openId);
		if (!isaccept) {
			results = osc.resultFailure("no", "");
			log.debug("更新骑手位置失败");
		} else {
			results = osc.resultSuccess("yes", "更新成功");
			log.debug("更新骑手位置成功");
		}
		return results;

	}
	/**
	 *
	 * @Description:
	 * 查找骑手位置
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresmanArea")
	public String findHoresmanArea(@RequestBody Map<String,String> map){
		log.debug("查找骑手位置！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		merchant merchant= merchantService.findHoresmanArea(openId);
		if (merchant==null) {
			results = osc.resultFailure("no", "");
			log.debug("查找骑手位置失败");
		} else {
			results = osc.resultSuccess("yes", merchant);
			log.debug("查找骑手位置成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 获取商家账户金额
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findMerchantAccount")
	public String findMerchantAccount(@RequestBody Map<String,String> map){
		log.debug("获取骑手账户金额！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<account> accounts = merchantService.findMerchantAccount(openId);
		if (accounts.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取骑手账户金额失败");
		} else {
			results = osc.resultSuccess("yes", accounts.get(0));
			log.debug("获取骑手账户金额成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取商家充值记录
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findrechargeRecord")
	public String findrechargeRecord(@RequestBody Map<String,String> map){
		log.debug("获取商家充值记录！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<recharge> recharges = merchantService.findrechargeRecord(openId);
		if (recharges.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取商家充值记录失败");
		} else {
			results = osc.resultSuccess("yes", recharges);
			log.debug("获取商家充值记录成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取商家提现记录
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findWithdrawRecord")
	public String findWithdrawRecord(@RequestBody Map<String,String> map){
		log.debug("获取商家提现记录！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<withdraw> withdraws = merchantService.findWithdrawRecord(openId);
		if (withdraws.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取商家提现记录失败");
		} else {
			results = osc.resultSuccess("yes", withdraws);
			log.debug("获取商家提现记录成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取商家骑手信息
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findHoresman")
	public String findHoresman(@RequestBody Map<String,String> map){
		log.debug("获取商家骑手信息！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		List<horseman> horesmen = merchantService.findHoresman(openId);
		if (horesmen.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取商家骑手信息失败");
		} else {
			results = osc.resultSuccess("yes", horesmen);
			log.debug("获取商家骑手信息成功");
		}
		return results;

	}

	/**
	 *
	 * @Description:
	 * 获取商家员工信息
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/findChildrenMerchant")
	public String findChildrenMerchant(@RequestBody Map<String,String> map){
		log.debug("获取商家员工信息！！！");
		String openId = map.get("openId");
		//返回结果
		String results ="";
		Map<String,List<Map<String,String>>> merchantsMap= merchantService.findChildrenMerchant(openId);
		if (merchantsMap.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取商家骑手信息失败");
		} else {
			results = osc.resultSuccess("yes", merchantsMap);
			log.debug("获取商家骑手信息成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 商家注册
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/registMerchant")
	public String registMerchant(@RequestBody Map<String,String> map){
		log.debug("商家注册！！！");
		String phone = map.get("phone");
		String password = map.get("password");
		String name = map.get("name");
		int code = Integer.parseInt(map.get("code"));
		String receivingtype =map.get("receivingtype");
		String merchantLat=map.get("merchantLat");
		String merchantLon=map.get("merchantLon");
		//返回结果
		String results ="";
		boolean isregist= merchantService.registMerchant(phone,password,name,code,receivingtype,merchantLat,merchantLon);
		if (!isregist) {
			results = osc.resultFailure("no", "");
			log.debug("商家注册失败");
		} else {
			results = osc.resultSuccess("yes", "");
			log.debug("商家注册成功");
		}
		return results;
	}

	/**
	 *
	 * @Description:
	 * 修改密码
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("/updatePassword")
	public String updatePassword(@RequestBody Map<String,String> map){
		log.debug("修改密码！！！");
		String password = map.get("password");
		String passwordOld = map.get("passwordOld");
		String openId = map.get("openId");
		//返回结果
		String results = "";
		boolean isregist= merchantService.updatePassword(password,passwordOld,openId);
		if (!isregist) {
			results = osc.resultFailure("no", "");
			log.debug("修改密码失败");
		} else {
			results = osc.resultSuccess("yes", "");
			log.debug("修改密码成功");
		}
		return results;

	}


	/**
	 *
	 * @Description:
	 * 查询门店信息经度纬度
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/16
	 * @param: [map]
	 * @return: map
	 *
	 */
	@ApiOperation("查询门店信息经度纬度")
	@PostMapping(value = "/selectLatLon",produces="text/html;charset=UTF-8;")
	public String selectLatLon(){
		List<merchant> sfidquerylist = merchantService.selectLatLon();
		String json= JSON.toJSONString(sfidquerylist);
		return json;
	}


	/**
	 *
	 * @Description:
	 * opeid查询门店geren信息
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/16
	 * @param: [map]
	 * @return: map
	 *
	 */
	@ApiOperation("查询门店信息个人信息")
	@PostMapping(value = "/selectidmerchant",produces="text/html;charset=UTF-8;")
	public String selectidmerchant(@RequestBody Map<String,String> map){
		String openid = map.get("openId");
		merchant merchantidselect = merchantService.selectidmerchant(openid);
		String json= JSON.toJSONString(merchantidselect);
		return json;
	}



	/**
	 *
	 * @Description:
	 * 用户生成门店订单
	 * @auther: 欧阳
	 * @date: 8:12 2021/11/20
	 * @param: [request]
	 * @return: java.lang.String
	 *
	 */
	@PostMapping("merchantaddOrder")
	public String merchantaddOrder(@RequestBody Map<String,String> map) {
		//返回结果
		String results="";
		packageOrder packageOrder = new packageOrder();
		if(StringUtils.isBlank(map.get("productType"))){
			return results = osc.failure("no");
		}
		if(StringUtils.isBlank(map.get("productId"))){
			return results = osc.failure("no");
		}
		log.debug("商户订单开始");
		String orderNumber = getOrderIdByTime();
		packageOrder.setOldIds("门店下单");
		packageOrder.setOrderNumber(orderNumber);
		packageOrder.setOrderTime(new Date());
		packageOrder.setProductType(map.get("productType"));
		packageOrder.setOrderExplain(map.get("explain"));
		packageOrder.setOpenId(map.get("openId"));
		packageOrder.setRecycleName(map.get("merchantName"));
		packageOrder.setRecycleNumber(map.get("merchantNumber"));
		packageOrder.setRecycleAddress(map.get("merchantArea"));
		packageOrder.setMerchantopenid(map.get("merchantopenid"));

		boolean isadd = horesmanService.merchaaddOrder(packageOrder,map.get("productId"));
		if(isadd) {
			results = osc.resultSuccess("yes",orderNumber);
			log.debug("添加订单成功");
		}else {
			results = osc.failure("no");
			log.debug("添加订单失败");
		}
		return results;
	}

	/**
	 *
	 * @Description:
	 * 查询门店下单信息
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/16
	 * @param: [map]
	 * @return: map
	 *
	 */
	@ApiOperation("查询门店下单信息")
	@PostMapping(value = "/merchantlist",produces="text/html;charset=UTF-8;")
	public String merchantlist(@RequestBody Map<String,String> map){
		String merchantopenid = map.get("merchantopenid");
		String orderstatus=map.get("orderstatus");
		List<order> merchantlist = merchantService.merchantlist(merchantopenid);
		String json= JSON.toJSONString(merchantlist);
		return json;
	}


	/**
	 *
	 * @Description:
	 * 获取商户各状态订单
	 * @auther: 欧阳辉
	 * @date: 11:33 2020/3/17
	 * @param: [map]
	 * @return: java.lang.String
	 *
	 */
	@ApiOperation("获取商户各状态订单")
	@PostMapping("/findmerchantOrder")
	public String findmerchantOrder(@RequestBody Map<String,String> map){
		log.debug("获取商户各状态订单！！！");
		String orderStatus = map.get("orderStatus");
		String openId = map.get("openId");
		String merchantopenid = map.get("merchantopenid");
		//返回结果
		String results ="";
		List<order> orders = horesmanService.findmerchantOrder(orderStatus,merchantopenid);
//        PageInfo horesmanOrder = horesmanService.findHoresmanOrder(orderStatus, openId, Integer.parseInt(page));
		if (orders.isEmpty()) {
			results = osc.resultFailure("no", "");
			log.debug("获取用户各状态订单失败");
		} else {
			results = osc.resultSuccess("yes", orders);
			log.debug("获取用户各状态订单成功");
		}
		return results;
	}




	/**
	 *
	 * @Description:
	 *
	 * 门店修改用户订单类型
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/16
	 * @param: [map]
	 * @return: map
	 *
	 */
	@ApiOperation("门店修改用户订单类型")
	@PostMapping(value = "/merchantupdatetype",produces="text/html;charset=UTF-8;")
	public String merchantupdatetype(@RequestBody Map<String,String> map){
		Map<String,String>maps=new HashMap<>();
		String payProductType = map.get("payProductType");
		String orderNumber=map.get("orderNumber");
		int res = merchantService.updatemerchanttype(orderNumber,payProductType);
		if(res==1){
			maps.put("message","200");
		}
		String json= JSON.toJSONString(maps);
		return json;
	}



	/**
	 *
	 * @Description:
	 *
	 * 门店支付用户
	 * @auther: 欧阳
	 * @date: 14:51 2021/11/16
	 * @param: [map]
	 * @return: map
	 *
	 */
	@ApiOperation("门店支付用户")
	@PostMapping(value = "/merchantpayuser",produces="text/html;charset=UTF-8;")
	public String merchantpayuser(@RequestBody Map<String,String> map){
		Map<String,String>maps=new HashMap<>();
		String orderId = map.get("orderId");

		Integer intorderid=Integer.valueOf(orderId).intValue();
		order order =merchantService.merchantpayuser(intorderid);
		//订单价格
		Double ordermoney=order.getPayOrderMoney();
		//商户id
		String merchantid=order.getMerchantopenid();
		//用户openid
		String userid=order.getOpenId();
		//商户金额
		account accountmerchant=merchantService.accountmoney(merchantid);
		Double merchantmoney=accountmerchant.getAccountMoneyBalance();

		//用户账户金额
		account accountuser=merchantService.accountmoney(userid);
		Double usermoney=accountuser.getAccountMoneyBalance();
		if(ordermoney>merchantmoney){
		System.out.println("钱都不够你支付尼玛啊");
		log.debug("商家你钱都不够了");
			maps.put("message","余额不足");
		}else{
			Double countmerchantmoney=merchantmoney-ordermoney;	//商户金额减去订单金额最后总金额
			Double countusermoney=usermoney+ordermoney;			//用户加上订单金额最后总金额
			account accmoney=new account();
			accmoney.setAccountMoneyBalance(countmerchantmoney);
			accmoney.setOpenId(merchantid);
			//商户执行修改余额
			int mesmerchatn=merchantService.accountupdatemoney(accmoney);
				System.out.println("成功啦.商家破产啦");
			//用户执行修改余额
			accmoney.setAccountMoneyBalance(countusermoney);
			accmoney.setOpenId(userid);
			int mesuser=merchantService.accountupdatemoney(accmoney);
			System.out.println("用户收钱成功啦发财啦.");

			cn.itcast.pojo.order order2= new order();
			order.setId(intorderid);
			int orderstatus=merchantService.orderupdate(order);
			System.out.println("商户"+countmerchantmoney);
			System.out.println("用户"+countusermoney);

			//商户记录表生成
			earnings earningsmerchant=new earnings();
			earningsmerchant.setAccountId(accountmerchant.getAccountId());
			earningsmerchant.setName(accountmerchant.getAccountName());
			earningsmerchant.setOpenid(accountmerchant.getOpenId());
			earningsmerchant.setSource("门店支付");
			earningsmerchant.setNumber(order.getOrderNumber());
			earningsmerchant.setNum(ordermoney);
			earningsmerchant.setState("已到账");
			earningsmerchant.setEarningsExplain("门店支付");
			earningsmerchant.setCountnum(countmerchantmoney);
			int earmerchant=merchantService.addearnings(earningsmerchant);

			//商户记录表生成
			earnings earningsuser=new earnings();
			earningsuser.setAccountId(accountuser.getAccountId());
			earningsuser.setName(accountuser.getAccountName());
			earningsuser.setOpenid(accountuser.getOpenId());
			earningsuser.setSource("门店支付");
			earningsuser.setNumber(order.getOrderNumber());
			earningsuser.setNum(ordermoney);
			earningsuser.setState("已到账");
			earningsuser.setEarningsExplain("门店支付");
			earningsuser.setCountnum(countusermoney);
			int usermerchant=merchantService.addearnings(earningsuser);

			maps.put("message","200");
		}

		String json= JSON.toJSONString(maps);
		return json;
	}




}






